﻿using StarPizza.Model.BaseModel;
using StarPizza.Model.User;
using StarPizza.ViewModel.User;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace StarPizza.ViewModel.ClientSystem
{
    class ClientDataEditor : AbstractClientData
    {
        StarDataDataContext db;
        
        public ClientDataEditor(StarDataDataContext db, UserSpace userSpace)
            :base(userSpace)
        {
            this.db = db;
            userSpace.AuthenticationStateChanged += userSpace_AuthenticationStateChanged;
        }

        //Login cannot be changed from outside, overriding the property
        //to hide inherited public accessor
        public new string Login
        {
            get { return base.Login; }
            private set
            {
                base.Login = value;
            }
        }

        void userSpace_AuthenticationStateChanged(AuthenticationState newState)
        {
            if (newState == AuthenticationState.On && userSpace.UserMode == UserMode.Client)
            {
                Client client = userSpace.LoggedInClient;
                Login = client.Login;
                Name = client.Name;
                District = client.District;
                Address = client.Address;
                Password = "";
            }
            if (newState == AuthenticationState.Off)
            {
                this.IsVisible = false;
            }
        }

        public void SaveClientData()
        {
            if (userSpace.UserMode == UserMode.Client)
            {
                Client client = userSpace.LoggedInClient;
                bool canSave = true;
                if (Password != "")
                {
                    if (Password == ConfirmedPassword)
                    {
                        client.Password = UserAuthenticator.EncryptPassword(Password);
                    }
                    else
                    {
                        MessageBox.Show(
                            messageBoxText: "Passwords do not match!",
                            caption: "Saving error",
                            button: MessageBoxButton.OK,
                            icon: MessageBoxImage.Error
                            );
                        canSave = false;
                    }
                }
                if (canSave) 
                {
                    client.Name = Name;
                    client.District = District;
                    client.Address = Address;
                    Utility.TrySubmitChanges(db);
                }
                Password = "";
                ConfirmedPassword = "";
            }
            this.IsVisible = false;
        }
        public void CancelEditing()
        {
            this.IsVisible = false;
        }
    }
}
